﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using eStock.hControl;
using HCommon;
using System.Data.SqlClient;
namespace eStock
{
    public partial class frmQuote_Add : hDialog
    {
        public frmQuote_Add()
        {
            InitializeComponent();
        }

        private void frmUser_Add_Load(object sender, EventArgs e)
        {
            LoadMaster();
            LoadGrid(this.UpdateKey);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (btnSave.Error == true) { btnSave.Error = false; return; }

            if (cboSTT.SelectedValue.ToString() == "STT00003")
            {
                DialogResult ds = MessageBox.Show("Bạn có chắc chắn muốn Chốt báo giá? Sau khi chốt bạn sẽ không thể thay đổi thông tin báo giá.", "Thông báo", MessageBoxButtons.YesNo);
                if (ds == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            if (Dao.objConn.State != ConnectionState.Open)
            {
                Dao.objConn.Open();
            }
            SqlTransaction objTrans = Dao.objConn.BeginTransaction();
            SaveMaster(objTrans);
        }

        private void SaveMaster(SqlTransaction objTrans)
        {
            try
            {
                int rs = 0;

                if (grdMain_Sum.Rows.Count == 0)
                {
                    Dialog.ShowMess(Dialog.mType.err, "Báo giá chưa có vật tư!");
                    return;
                }

                if (grdMain_Sum.Rows[0].Cells["TotalAmt"].Value == null)
                {
                    Dialog.ShowMess(Dialog.mType.err, "Tổng giá trị của báo giá phải lớn hơn 0!");
                    return;
                }

                // Bắt đầu transaction
                Dao.BeginTrans(ref objTrans);

                string QuoteNo = "";


                if (this.FormMode == Mode.Insert)
                {
                    DataTable dt = new DataTable();
                    dt = Dao.Get_Table("Exec P_GetQuoteNo N'" + Settings.myUserName + "'", objTrans);
                    if (dt.Rows.Count == 0)
                    {
                        Dao.RollBackTrans(objTrans);
                        Dialog.ShowMess(Dialog.mType.err, "Không lấy được mã báo giá");
                        return;
                    }
                    QuoteNo = Settings.myUserCode + dt.Rows[0]["QuoteNo"].ToString() + "-B" + DateTime.Now.ToString("MMyy");

                    rs = tblQuote.Insert(QuoteNo, txtCustomerCd.Text, txtContent.Text, grdMain_Sum.Rows[0].Cells["TotalAmt"].Value.ToString(), cboSTT.SelectedValue.ToString(), txtPhoneNo.Text, txtFaxNo.Text, txtAddr.Text, txtReceiver.Text, txtPosition.Text, txtHomePhone.Text, txtEmail.Text, objTrans);
                }
                else
                {
                    QuoteNo = this.UpdateKey;
                    rs = tblQuote.Update(QuoteNo, txtCustomerCd.Text, txtContent.Text, grdMain_Sum.Rows[0].Cells["TotalAmt"].Value.ToString(), cboSTT.SelectedValue.ToString(), txtPhoneNo.Text, txtFaxNo.Text, txtAddr.Text, txtReceiver.Text, txtPosition.Text, txtHomePhone.Text, txtEmail.Text, objTrans);
                }

                if (rs == 0)
                {
                    Dao.RollBackTrans(objTrans);
                    Dialog.ShowMess(Dialog.mType.err, "Lưu dữ liệu không thành công");
                    return;
                }

                SaveGrid(QuoteNo, objTrans);
            }
            catch (Exception ex)
            {
                Dao.RollBackTrans(objTrans);
                Common.GhiLog("SaveMaster", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
        }

        private void LoadMaster()
        {
            try
            {
                if (this.FormMode == Mode.Insert)
                {
                    Common.ClearControl(grbQuote);
                    return;
                }

                DataTable dt = new DataTable();
                dt = Dao.Get_Table("SELECT * FROM tblQuote with(nolock) where QuoteNo = N'" + this.UpdateKey + "'");
                if (dt.Rows.Count == 0)
                {
                    Dialog.ShowMess(Dialog.mType.err, "Báo giá này đã bị xóa!");
                    this.Close();
                    return;
                }

                txtQuoteNo.Text = dt.Rows[0]["QuoteNo"].ToString();
                txtCreateBy.Text = dt.Rows[0]["CreateBy"].ToString();
                txtCreateDate.Text = dt.Rows[0]["CreateDate"].ToString();
                cboSTT.SelectedValue = dt.Rows[0]["Status"].ToString();

                txtCustomerCd.Text = dt.Rows[0]["CustomerCd"].ToString();
                txtContent.Text = dt.Rows[0]["Content"].ToString();
                txtPhoneNo.Text = dt.Rows[0]["PhoneNo"].ToString();
                txtFaxNo.Text = dt.Rows[0]["FaxNo"].ToString();
                txtAddr.Text = dt.Rows[0]["Addr"].ToString();
                txtReceiver.Text = dt.Rows[0]["Receiver"].ToString();
                txtPosition.Text = dt.Rows[0]["Position"].ToString();
                txtHomePhone.Text = dt.Rows[0]["HomePhone"].ToString();
                txtEmail.Text = dt.Rows[0]["Email"].ToString();
            }
            catch (Exception ex)
            {
                Common.GhiLog("LoadMaster", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
        }

        private void SaveGrid(string QuoteNo, SqlTransaction objTrans)
        {
            try
            {
                int rs = 0;
                foreach (DataGridViewRow row in grdMain.Rows)
                {
                    try
                    {
                        if (row.Cells["ItemCd"].Value == null || row.Cells["ItemCd"].Value.ToString().Trim().Length == 0)
                        {
                            continue;
                        }
                        if (row.IsNewRow == true)
                        {
                            continue;
                        }
                        if (Double.Parse(row.Cells["Quantity"].Value.ToString()) > Double.Parse(row.Cells["TonDuocBan"].Value.ToString()))
                        {
                            row.Cells["ErrMsg"].Value = "Số lượng đặt không được lớn hơn số lượng tồn được bán";
                            row.DefaultCellStyle.ForeColor = Color.Red;
                            grdMain.SaveGridErr = true;
                            continue;
                        }

                        int ID = 0;
                        if (row.Cells["ID"].Value == null || row.Cells["ID"].Value.ToString().Trim().Length == 0)
                        {
                            ID = tblQuote_Item.Insert(QuoteNo, row.Cells["ItemCd"].Value.ToString(), row.Cells["Quantity"].Value.ToString(), row.Cells["Price"].Value.ToString(), row.Cells["Amount"].Value.ToString(), objTrans);
                            row.Cells["ID"].Value = ID;
                            rs++;
                        }
                        else
                        {
                            rs += tblQuote_Item.Update(QuoteNo, row.Cells["ID"].Value.ToString(), row.Cells["ItemCd"].Value.ToString(), row.Cells["Quantity"].Value.ToString(), row.Cells["Price"].Value.ToString(), row.Cells["Amount"].Value.ToString(), objTrans);
                        }
                        row.Cells["ErrMsg"].Value = "";
                        row.DefaultCellStyle.ForeColor = Color.Black;
                    }
                    catch (Exception ex)
                    {
                        row.Cells["ErrMsg"].Value = ex.Message;
                        row.DefaultCellStyle.ForeColor = Color.Red;
                        grdMain.SaveGridErr = true;
                        Common.GhiLog("SaveGrid_foreach", ex);
                    }
                }
                Dao.CommitTrans(objTrans);
                Dialog.ShowMess(Dialog.mType.ok, "Đã lưu thành công Báo giá số: " + QuoteNo + ". (Báo giá bao gồm " + rs.ToString() + " vật tư)");

                this.UpdateKey = QuoteNo;
                this.FormMode = Mode.Update;
                LoadMaster();
                if (grdMain.SaveGridErr == false)
                {
                    LoadGrid(QuoteNo);
                }
            }
            catch (Exception ex)
            {
                Dao.RollBackTrans(objTrans);
                Common.GhiLog("SaveGrid", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
            finally { grdMain.SaveGridErr = false; }
        }

        private void LoadGrid(string QuoteNo)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = Dao.Get_Table("Exec spQuote_Item_Q '" + QuoteNo + "'");
                if (dt != null)
                {
                    grdMain.DataSource = dt;
                }
                grdMain.SummaryCalc();

                if (cboSTT.SelectedValue.ToString() == "STT00003") 
                {
                    btnSave.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Common.GhiLog("LoadGrid", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
        }

        // Load thông tin khách hàng
        private void txtCustomerCd_Leave(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = Dao.Get_Table("SELECT * FROM tblCustomer with(nolock) where CustomerCd = '" + Common.xoaNhay(txtCustomerCd.Text) + "'");
                if (dt.Rows.Count == 0)
                {
                    return;
                }
                txtPhoneNo.Text = dt.Rows[0]["PhoneNo"].ToString();
                txtFaxNo.Text = dt.Rows[0]["FaxNo"].ToString();
                txtAddr.Text = dt.Rows[0]["Addr"].ToString();
                txtReceiver.Text = dt.Rows[0]["Receiver"].ToString();
                txtPosition.Text = dt.Rows[0]["Position"].ToString();
                txtHomePhone.Text = dt.Rows[0]["HomePhone"].ToString();
                txtEmail.Text = dt.Rows[0]["Email"].ToString();
            }
            catch (Exception ex)
            {
                Common.GhiLog("txtCustomerCd_Leave", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
        }

        private void txtCustomerCd_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = Dao.Get_Table("SELECT * FROM tblCustomer with(nolock) where CustomerCd = '" + Common.xoaNhay(txtCustomerCd.Text) + "'");
                if (dt.Rows.Count == 0)
                {
                    return;
                }
                txtPhoneNo.Text = dt.Rows[0]["PhoneNo"].ToString();
                txtFaxNo.Text = dt.Rows[0]["FaxNo"].ToString();
                txtAddr.Text = dt.Rows[0]["Addr"].ToString();
                txtReceiver.Text = dt.Rows[0]["Receiver"].ToString();
                txtPosition.Text = dt.Rows[0]["Position"].ToString();
                txtHomePhone.Text = dt.Rows[0]["HomePhone"].ToString();
                txtEmail.Text = dt.Rows[0]["Email"].ToString();
            }
            catch { }
        }

        private void grdMain_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (grdMain.Columns[e.ColumnIndex].Name == "ItemCd")
                {
                    LoadItem(e);
                }
                else if (grdMain.Columns[e.ColumnIndex].Name == "Quantity" || grdMain.Columns[e.ColumnIndex].Name == "Price")
                {
                    grdMain.Rows[e.RowIndex].Cells["Amount"].Value = Double.Parse(grdMain.Rows[e.RowIndex].Cells["Quantity"].Value.ToString()) * Double.Parse(grdMain.Rows[e.RowIndex].Cells["Price"].Value.ToString());
                }
            }
            catch { }
        }

        private void LoadItem(DataGridViewCellEventArgs e)
        {
            DataTable dt = new DataTable();
            dt = Dao.Get_Table("Exec spItem_Q '" + grdMain.Rows[e.RowIndex].Cells["ItemCd"].Value.ToString() + "','','',''");
            if (dt.Rows.Count == 0)
            {
                grdMain.Rows[e.RowIndex].Cells["ItemName"].Value = string.Empty;
                grdMain.Rows[e.RowIndex].Cells["UnitName"].Value = string.Empty;
                grdMain.Rows[e.RowIndex].Cells["OriginName"].Value = string.Empty;
                grdMain.Rows[e.RowIndex].Cells["Price"].Value = 0;
                grdMain.Rows[e.RowIndex].Cells["TonDuocBan"].Value = 0;
                return;
            }
            grdMain.Rows[e.RowIndex].Cells["ItemName"].Value = dt.Rows[0]["ItemName"].ToString();
            grdMain.Rows[e.RowIndex].Cells["UnitName"].Value = dt.Rows[0]["UnitName"].ToString();
            grdMain.Rows[e.RowIndex].Cells["OriginName"].Value = dt.Rows[0]["OriginName"].ToString();
            grdMain.Rows[e.RowIndex].Cells["Price"].Value = dt.Rows[0]["Price"].ToString();
            grdMain.Rows[e.RowIndex].Cells["TonDuocBan"].Value = dt.Rows[0]["TonDuocBan"].ToString();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            this.FormMode = Mode.Insert;
            LoadMaster();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void grdMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (grdMain.Columns[e.ColumnIndex].Name == "ItemCd")
                {
                    return;
                }

                if (grdMain.Rows[e.RowIndex].Cells["ItemCd"].Value == null || grdMain.Rows[e.RowIndex].Cells["ItemCd"].Value.ToString().Trim().Length == 0)
                {
                    return;
                }
                if (cboSTT.SelectedValue.ToString() != "STT00001" && cboSTT.SelectedValue.ToString() != "STT00002")
                {
                    Dialog.ShowMess(Dialog.mType.warn, "Không thể chỉnh sửa báo giá đã được chốt");
                    return;
                }
                frmItems_Add ItemAdd = new frmItems_Add();
                ItemAdd.UpdateKey = grdMain.Rows[e.RowIndex].Cells["ItemCd"].Value.ToString();
                ItemAdd.FormMode = Mode.Update;
                ItemAdd.ShowDialog();
                if (ItemAdd != null)
                {
                    LoadItem(e);
                }
            }
            catch { }
        }

        private void cboSTT_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboSTT.SelectedValue.ToString() == "STT00001" || cboSTT.SelectedValue.ToString() == "STT00002")
                {
                    grdMain.ReadOnly = false;
                }
                else
                {
                    grdMain.ReadOnly = true;
                }
            }
            catch { }
        }

        private void grdMain_hDelete(object sender, EventArgs e)
        {
            try
            {
                if (cboSTT.SelectedValue.ToString() != "STT00001" && cboSTT.SelectedValue.ToString() != "STT00002")
                {
                    Dialog.ShowMess(Dialog.mType.warn, "Không thể chỉnh sửa báo giá đã được chốt");
                    return;
                }
                int delCnt = 0;
                foreach (DataGridViewRow row in grdMain.SelectedRows)
                {
                    if (row.IsNewRow == true)
                    {
                        continue;
                    }
                    if (tblQuote_Item.Delete(row.Cells["ID"].Value.ToString()) > 0)
                    {
                        grdMain.Rows.Remove(row);
                        delCnt++;
                    }
                }
                Dialog.ShowMess(Dialog.mType.ok, "Đã xóa thành công " + delCnt + " bản ghi.");
            }
            catch (Exception ex)
            {
                Common.GhiLog("grdMain_hDelete", ex);
                Dialog.ShowMess(Dialog.mType.err, ex.Message);
            }
        }
    }
}
